import type { UserInfo } from '@/apis/auth'
import * as authApi from '@/apis/auth'

export const useUserStore = defineStore('user', () => {
  const token = useAppLocalStorage<string>('token', '')

  const setToken = (newToken: string) => {
    token.value = newToken
  }

  const clearToken = () => {
    token.value = null
  }

  const isLogin = computed(() => !!token.value)

  const user = ref<UserInfo>()

  const isLoadInfo = computed(() => !!user.value)

  /**
   * 登录
   * @param data 登录参数
   */
  const login = async (data: authApi.LoginParams) => {
    const { token } = await authApi.login(data)
    setToken(token)
    await refInfo()
  }

  /**
   * 退出登录
   */
  const logout = () => {
    clearToken()
    user.value = undefined
  }

  /**
   * 刷新用户信息
   */
  const refInfo = async () => {
    if (!isLogin.value) return
    user.value = await authApi.info()
  }

  // 判断是否登录, 如果登录并且没有加载用户信息, 则加载用户信息
  watchEffect(async () => {
    if (isLogin.value && !isLoadInfo.value) {
      await refInfo()
    }
  })

  return {
    // token相关
    token,
    setToken,
    clearToken,

    // 状态判断相关
    isLogin,

    // 用户信息相关
    user,
    isLoadInfo,
    login,
    logout,
    refInfo,
  }
})
